﻿/// <reference path="../app.ts" />
/// <reference path="../models/userInfoModel.ts" />
/// <reference path='../../typings/angularjs/angular.d.ts'/>
/// <reference path='../../typings/angularjs/angular-resource.d.ts'/>

appRoot.factory('staticObjects', ['$rootScope', 'notificationFactory', '$location', ($rootScope, notificationFactory, $location) => {
    var getMessageByInternalCode = internalCode => { 
        var message = "";
        switch (internalCode)
        {
        case 1000:
            message = "Another report already generating.";
            break;
        case 1001:
            message = "Generating the report failed - Please contact your Administrator";
            break;
        case 1002:
            message = "Total number of concurrent users per application reached!";
            break;
        case 1003:
            message = "Login failed";
            break;
        case 1004:
            message = "The combination of username and password is incorrect. Please check and try again.";
            break;
        case 1011:
            message = "An error has occurred while reseting passwords. Please try again later.";
            break;
        case 1013:
            message = "There was an error while retrieving the users. Please try again later.";
            break;
        case 1014:
            message = "There was an error while retrieving accounts. Please try again later.";
            break;
        case 1015:
            message = "There was an error while retrieving the selected user. Please try again later.";
            break;
        case 1016:
            message = "There was an error while retrieving the selected account. Please try again later.";
            break;
        case 2001: // News_PublishNonDraftNews
            message = "Only items in status Draft can be published. Please check your selection and try again.";
            break;
        case 2002: // News_NewsIsNull
            message = "News is null.";
            break;
        case 2003: // News_NewsNotValid
        case 2004: // News_NewsNotValid_TitleNullOrEmpty
            message = "Please check the following field(s): <br/>Article title, <br/>Date, <br/>Region, <br/>Unpublished date, <br/>Body";
            break;
        case 2005: // News_NewsNotValid_TitleLength
            message = "Please make sure that you do not insert more than 100 characters with spaces in the Article Title field.";
            break;
        case 2006: // News_DoesNotExist
            message = "News does not exist.";
            break;
        case 2007: // News_DateCreated_NotValid
        case 2008: // News_UnpublishedDate_NotValid
            message = "Please enter the date as MM/DD/YYYY";
            break;
        case 2015: // News_DeleteNonDraftNews
            message = "Only items in status Draft can be deleted. Please check your selection and try again.";
            break;

        // insights errors
        case 2100:
            message = "Please select a sector"; break;
        case 2101:
            message = "Please select a topic"; break;
        case 2102:
            message = "Please type a title"; break;
        case 2103:
            message = "Please make sure that you do not insert more than 100 characters with spaces in the Title of Publication field"; break;
        case 2104:
            message = "Please select a publish date"; break;
        case 2105:
            message = "Please enter the date as MM/DD/YYYY"; break;
        case 2106:
            message = "Please select a un-publish date"; break;
        case 2107:
            message = "Please upload a publication file, the supported file format is PDF, max. 10M in size"; break;
        case 2108:
            message = "The supported file format is PDF, max. 10M in size"; break;
        case 2109:
            message = "Please upload a image, the supported file formats are jpg or png of 200 x 251 pixels"; break;
        case 2110:
            message = "The supported file formats are jpg or png of 200 x 251 pixels"; break;
        case 2111:
            message = "Please type a summary"; break;
        case 2112:
            message = "Please make sure that you do not insert more than 5000 characters with spaces in the Summary field"; break;
        case 2113:
            message = "Unpublished date must be bigger than published date"; break;
        case 2114:
            message = "Upload failed, plase try again"; break;
        // governance company search
        case 6015:
            message = "You do not have the necessary rights to access this page. Please contact your account manager for details.";
            break;

        // product involvement 
            case 2200: message = "File is not *.xls or *.xlsx"; break;
            case 2210: message = "Upload file failed"; break;
        //news, events and insights error
        case 3003:
            message = "You do not have the necessary rights to access this page. Please contact your account manager for details.";
            break;
        case 9999:
            message = "You are not authorized to use the Administration section.";
            break;

        default:
            message = "An error has occurred. Please contact your administrator!";
            break;
        }
        return message;
    };
    var staticObjects: IStaticObjects = {
        apiBaseUrl: "api/",
        authBaseUrl: "/security",
        eventsServiceBaseUrl: "/eventsserv",
        getMessageByInternalCode: getMessageByInternalCode,
        getErrorMesageByStatusCode: (statusCode, data) => {
            var message = "";
            switch (statusCode) {
            case 401:
                message = "Unauthorized";
                break;
            case 500:
                if (data && data.code) { message = getMessageByInternalCode(data.code); }
                else {
                    message = "An error has occurred. Please contact your administrator!";
                }
                break;
            case 404:
                message = "Resource not found";
                break;
            case 400:
                message = "Bad request. Resource not found";
                break;
            default:
                message = "Unknown error";
                break;
            }
            return message;
        },
        errorCallback: (error, status, internalCode) => {
            if (error != "") {
                notificationFactory.error(error.exceptionMessage, error.message);
            } else {
                notificationFactory.error("", staticObjects.getErrorMesageByStatusCode(status, internalCode));
            }
        },
        initSignalR: () => {
            if ($rootScope.authData && $rootScope.authData.access_token)
            {
                $.connection.hub.qs = { "access_token" : $rootScope.authData.access_token};
                $.connection.hub.start()
                    .done(() =>
                    {
                    })
                    .fail(error =>
                    {
                        //alert(error.message);
                        notificationFactory.error("SignalR failed to initialize!\n" + error.message, "SignalR error");
                    });
            }
        },
        clearUserInfo: () => {
            $rootScope.userInfo = new UserInfoClass();
            var authData: Sustainalytics.Authentication.AuthData = { expires_in: null, access_token: null, refresh_token: null, loginTime:null };
            $rootScope.authData = authData;
            staticObjects.resourcePermissions = "";
        }, 
        redirectToLogin:() => {
            if ($location.path() != '/login') {
                $location.url('/login');
                //if (!$rootScope.$$phase) { $rootScope.$apply(); }
            }
        },
        redirectToDefault: (redirectTo?: string) => {
            if (redirectTo) {
                $location.url(redirectTo);
            }
            else {
                if ($location.path() != '/') {
                    $location.url('/');
                    //if (!$rootScope.$$phase) { $rootScope.$apply(); }
                }
            }
        },
        redirectToLink: (link) => {
            if ($location.path() != link) {
                $location.url(link);
            }
        },
        resourcePermissions: "",
        authDataIsExpired: (authData: Sustainalytics.Authentication.AuthData) => {
            if (!authData.loginTime) {
                return true;
            }
            var day = authData.loginTime.getDay();
            var month = authData.loginTime.getMonth();
            var year = authData.loginTime.getFullYear();
            var hours = authData.loginTime.getHours();
            var minutes = authData.loginTime.getMinutes();
            var seconds = authData.loginTime.getSeconds();

            var endDate = new Date(year, month, day, hours, minutes, seconds + authData.expires_in);////
            var now = new Date();

            if (endDate > now) {
                return true;
            } else {
                return false;   
            }
        }
    };
    return staticObjects;
}]);